<template>
  <div>
    <div class="home-page">
      <div class="banner">
        <div class="container">
          <h1 class="logo-font">conduit</h1>
          <p>A place to share your knowledge.</p>
        </div>
      </div>

      <div class="container page">
        <div class="row">
          <div class="col-md-9">
            <!-- 导航栏  -->
            <div class="feed-toggle">
              <ul class="nav nav-pills outline-active">
                <li class="nav-item" v-if="user">
                  <nuxt-link
                    class="nav-link"
                    :class="{
                      active: tab === 'your_feed',
                    }"
                    :to="{
                      name: 'home',
                      query: {
                        tab: 'your_feed',
                      },
                    }"
                    exact
                    >Your Feed</nuxt-link
                  >
                  <!-- 使用exact精确匹配来使得二者不会因为都是以/ 开头被同时选中 -->
                </li>

                <li class="nav-item">
                  <nuxt-link
                    class="nav-link"
                    :class="{
                      active: tab === 'global_feed',
                    }"
                    :to="{
                      name: 'home',
                      query: {
                        tab: 'global_feed',
                      },
                    }"
                    exact
                    >Global Feed</nuxt-link
                  >
                </li>

                <li class="nav-item" v-if="tag">
                  <nuxt-link
                    class="nav-link"
                    :class="{
                      active: tab === 'tag',
                    }"
                    :to="{
                      name: 'home',
                      query: {
                        tab: 'tag',
                        tag: tag,
                      },
                    }"
                    exact
                    >#{{ tag }}</nuxt-link
                  >
                </li>
              </ul>
            </div>

            <!-- 导航栏中的内容、文章 -->
            <div
              class="article-preview"
              v-for="article in articles"
              :key="article.slug"
            >
              <div class="article-meta">
                <nuxt-link
                  :to="{
                    name: 'profile',
                    params: {
                      username: article.author.username,
                    },
                  }"
                  ><img :src="article.author.image"
                /></nuxt-link>
                <div class="info">
                  <nuxt-link
                    :to="{
                      name: 'profile',
                      params: {
                        username: article.author.username,
                      },
                    }"
                    class="author"
                    >{{ article.author.username }}</nuxt-link
                  >
                  <span class="date">{{
                    article.createdAt | date("MMM DD, YYYY")
                  }}</span>
                </div>
                <button
                  class="btn btn-outline-primary btn-sm pull-xs-right"
                  :class="{
                    active: article.favorited,
                  }"
                  @click="onFavorite(article)"
                  :disabled="article.favoriteDisabled"
                >
                  <i class="ion-heart"></i> {{ article.favoritesCount }}
                </button>
              </div>
              <nuxt-link
                :to="{
                  name: 'article',
                  params: {
                    slug: article.slug,
                  },
                }"
                class="preview-link"
              >
                <h1>{{ article.title }}</h1>
                <p>{{ article.description }}</p>
                <span>Read more...</span>
              </nuxt-link>
            </div>

            <!-- 分页列表 -->
            <nav>
              <ul class="pagination">
                <li
                  class="page-item"
                  v-for="item in totalPage"
                  :key="item"
                  :class="{
                    active: item === page,
                  }"
                >
                  <nuxt-link
                    class="page-link ng-binding"
                    :to="{
                      name: 'home',
                      query: {
                        page: item,
                        tag: $route.query.tag,
                        tab: tab,
                      },
                    }"
                    >{{ item }}</nuxt-link
                  >
                  <!-- 这里使用nuxt-link方式进行跳转的缺点就是不会走服务端的asyncData方法，
                  并且query的改变也不会触发页面的更新，但是页码相关设置都是定义在asyncData中的，
                  所以需要启动watchQuery监听query中的成员变化也就是query参数变化来实现asyncData的执行 -->
                </li>
              </ul>
            </nav>
          </div>

          <!-- tags 标签 -->
          <div class="col-md-3">
            <div class="sidebar">
              <p>Popular Tags</p>

              <div class="tag-list">
                <nuxt-link
                  :to="{
                    name: 'home',
                    query: {
                      tag: item,
                      tab: 'tag',
                    },
                  }"
                  class="tag-pill tag-default"
                  v-for="(item, index) in tags"
                  :key="index"
                  >{{ item }}</nuxt-link
                >
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getArticles, getFeedArticles, addFavorite,deleteFavorite } from "@/api/article";
import { getTags } from "@/api/tag";
import { mapState } from "vuex";
export default {
  name: "HomeIndex",
  async asyncData({ query, store }) {
    const limit = 20;
    const page = Number.parseInt(query.page || 1);
    const { tag } = query;
    const tab = query.tab || "global_feed";
    const loadArticels =
      store.state.user && tab === "your_feed" ? getFeedArticles : getArticles;
    // 使用Promise.all 对非依赖关系的请求进行并行处理，提升访问速度
    const [articleRes, tagRes] = await Promise.all([
      loadArticels({
        limit,
        offset: (page - 1) * limit,
        // limit是单页限制的文章个数（最大个数）
        // offset是偏移量，表示跳过的文章个数，比如limit=2时，offset=2就表示第二页
        tag,
      }),
      // 不传参数默认获取所有文章
      // console.log(data);

      getTags(),
      // console.log(tagData);
    ]);

    const { articles, articlesCount } = articleRes.data;
    const { tags } = tagRes.data;

    articles.forEach(article => {
      article.favoriteDisabled = false
    });
    return {
      articles,
      articlesCount,
      page,
      limit,
      tags,
      tag,
      tab: query.tab || "global_feed",
    };
  },

  // 监听query参数中的成员变化，指定的成员变化后会触发asyncData,默认是关闭的
  watchQuery: ["page", "tag", "tab"],
  computed: {
    totalPage() {
      return Math.ceil(this.articlesCount / this.limit);
    },
    ...mapState(["user"]),
  },
  methods: {
    async onFavorite(article) {
      // 防止频繁点击点赞按钮导致的赞数异常增加，因为有些时候由于网络延迟还没有给
      // 当前文章添加上favorited状态，所以还会能接着调用点赞接口，导致赞数一直增加
      // 所以这里在点赞发起后进行了点赞按钮禁用，直到新增的favorited状态已经添加上再解禁
      article.favoriteDisabled = true
      if (article.favorited) {
        // 取消点赞
        await deleteFavorite(article.slug);
        article.favorited = false;
        article.favoritesCount -= 1;
      } else {
        // 添加点赞
        await addFavorite(article.slug);
        article.favorited = true;
        article.favoritesCount += 1;
      }
      article.favoriteDisabled = false
    },
  },
};
</script>

<style scoped></style>
